<?php

include_once('Logging.php');

//include_once ('Tools.php');

class SFExpressClass1
{

    const API_BASE_URL = 'http://bspoisp.sit.sf-express.com:11080/bsp-ois/sfexpressService';     //正式
    const API_BASE_URL_TEST ='https://commit-openic.sf-express.com/open/api/external/createorder';//http://218.17.248.244:11080/bsp-oisp/sfexpressService';//'https://bsp-ois.sit.sf-express.com:9443/bsp-ois/sfexpressService' ;    //测试

    const USERNAME = 'BSPdevelop';
    const USERNAME_TEST = 'SHYZDZ';
    const CHECKWORD='j8DzkIFgmlomPt0aLuwU';
    const CHECKWORD_TEST='kmX6QezC4FC4';

    private $isDebug = false;

    public function __construct($flag)
    {
        $this->isDebug = $flag;
    }



    /*
     *   路由查询
   */
    public function routeService($tracking_number)
    {
        $url = (($this->isDebug) ? self::API_BASE_URL_TEST : self::API_BASE_URL);
        $username = (($this->isDebug) ? self::USERNAME_TEST : self::USERNAME);
        $checkword = (($this->isDebug) ? self::CHECKWORD_TEST : self::CHECKWORD);
        //$xml="<Request service='RouteService' lang='zh-CN'><Head>".$username."</Head><Body><RouteRequest tracking_type='1' method_type='1' tracking_number='616567411548'/></Body></Request>";
$xml="<Request service='RouteService' lang='zh-CN'>     
<Head>".$username."</Head>
<Body>
<RouteRequest
tracking_type='1'
method_type='1'
tracking_number='".$tracking_number."'/>
</Body>
</Request>
";


        $data=$xml.$checkword;
        $md5=md5($data, true );
        $verifyCode=base64_encode($md5);
        $param =array(
            'xml' => $xml,
            'verifyCode' => $verifyCode,
        );

         $result = $this->http_post($url, $param,false,'','signnature:'.$xml.$checkword.','.$md5);
/*
        $result='<Response service="RouteService">';
        $result.='<Head>OK</Head>';
        $result.='<Body>';
        $result.='<RouteResponse mailno="444003077898">';
        $result.='<Route accept_time="2015-01-04 8:11:26" accept_address="深圳" remark="已取货" opcode="50"/>';
        $result.='<Route accept_time="2015-01-04 10:11:26" accept_address="深圳" remark="已收件" opcode="50"/>';
        $result.='<Route accept_time="2015-01-05 17:41:50" remark="此件签单返还的单号为 123638813180" opcode="922"/>';
        $result.='</RouteResponse>';
        $result.='</Body>';
        $result.='</Response>';

        $result='<Response service="RouteService">
<Head>ERR</Head>
<ERROR code="4001">系统发生数据错误或运行时异常</ERROR>
</Response>
';
*/
        //$xml = simplexml_load_string($result, "SimpleXMLElement", LIBXML_NOCDATA);
        $array = json_decode($result,TRUE);
        $json = json_encode($array, JSON_UNESCAPED_UNICODE);
       //

        return $json;

    }



    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    private function http_post($url, $param, $post_file = false, $contenttype = '', $msg = '')
    {
        $log = new Logging();
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (empty($contenttype)) {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded'));
        } else if ($contenttype == "json") {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));

        }

        $strPOST='';
        if (is_string($param)) {
            $strPOST = $param;
        } else {
            $aGET = array();
            foreach ($param as $key => $val) {
                $aGET[] = $key . "=" . ($val);
            }
            $strPOST = join("&", $aGET);
        }

        //$strPOST=http_build_query($param, '', '&');

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);


        $time=strtotime(date('Y-m-d H:i:s'));
        $log->lfile('sf_express');
        $log->lwrite($time.','.($url));
        $log->lwrite($time.','.$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);

        $log->lwrite($time.','.($sContent));

        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }


    private $log_file = '/tmp/logfile.log';
    // define file pointer
    private $fp = null;
    private $filepath = null;

    // set log file (path and name)
    private function setPath() {
        $serverFilePath = $_SERVER["SCRIPT_FILENAME"];//realpath(dirname(__FILE__));//$_SERVER["SCRIPT_FILENAME"];
        $doc_dir = strrpos($serverFilePath, '/');
        $doc_dir = substr($serverFilePath, 0, $doc_dir + 1);   //project root

        $this->mkdir_r($doc_dir . 'logs');
        $this->filepath = $doc_dir . 'logs';
    }

    public function mkdir_r($dir, $rights = 0777) {
        if (!is_dir($dir)) {
            $dirs = explode('/', $dir);
            $dir2 = '';
            foreach ($dirs as $part) {
                $dir2.=$part . '/';
                if (!is_dir($dir2) && strlen($dir2) > 0) {
                    mkdir($dir2, 0777);
                }
            }
        }
    }

    public function lfile($filename) {
        $this->log_file = $this->filepath . '/' . $filename;
    }

    // write message to the log file
    public function lwrite($message) {
        // if file pointer doesn't exist, then open log file
        if (!$this->fp)
            $this->lopen();
        // define script name
        $script_name = isset($_SERVER["HTTP_HOST"])?$_SERVER["HTTP_HOST"]:"localhost";
        // define current time
        $time = date('H:i:s');
        // write current time, script name and message to the log file
        fwrite($this->fp, "$time ($script_name) $message\n");
    }

    // open log file
    private function lopen() {
        // define log file path and name
        $lfile = $this->log_file;
        // define the current date (it will be appended to the log file name)
        $today = date('Y-m-d');
        // open log file for writing only; place the file pointer at the end of the file
        // if the file does not exist, attempt to create it
        $this->fp = fopen($lfile . '_' . $today . '.log', 'a') or exit("Can't open $lfile!");
    }


}

?>